package org.gnome.wsgalaxy.gnodroid;

import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.List;

public class ServiceAppmanager extends ServiceBase {
    Socket m_socket = null;

    @Override
    public void
    start(byte[] firstData, Socket socket) {

        m_socket = socket;
        try {
            String recStr = new String(firstData, "UTF-8");
            JSONObject recJson = new JSONObject(recStr);
            String method = recJson.getString("method");
            switch (method) {
                case "GetAppList":
                    __methodGetAppList();
                    break;
                case "GetAppIcon":
                    __methodGetAppIcon(recJson.getString("package_name"));
                    break;
                default:
                    throw new Exception("no such method");
            }
        } catch (Exception e) {

        }

    }


    void
    __methodGetAppList() {

        try {
            PackageManager pm = Global.SERVICE_CONTEXT.getPackageManager();
            List<PackageInfo> listPackageInfo = pm.getInstalledPackages(0);

            JSONObject resJson = new JSONObject();
            resJson.put("service", "Appmanager");
            resJson.put("method", "GetAppList");

            JSONArray appUserList = new JSONArray();
            JSONArray appSystemList = new JSONArray();

            for (PackageInfo pinfo : listPackageInfo) {
                JSONObject newApp = new JSONObject();
                newApp.put("label", pinfo.applicationInfo.loadLabel(pm).toString());
                newApp.put("package_name", pinfo.packageName == null ? "None" : pinfo.packageName);
                newApp.put("version", pinfo.versionName == null ? "None" : pinfo.versionName);

                if ((pinfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                    // user app
                    appUserList.put(newApp);
                } else {
                    // system app
                    appSystemList.put(newApp);
                }
            }

            resJson.put("app_user", appUserList);
            resJson.put("app_system", appSystemList);

            Log.d("gnd", resJson.toString());
            String dJsonStr = resJson.toString();

            byte[] resData = Global.JsonToByte(resJson);
            if (resData == null) {
                throw new Exception("get byte failed");
            }

            OutputStream outputStream = m_socket.getOutputStream();
            outputStream.write(resData);
            m_socket.close();
        } catch (Exception e) {
            Log.d("gnd", "Appmanager failed" + e.toString());
        }
    }

    void
    __methodGetAppIcon(String packageName) {

        try {
            PackageManager pm = Global.SERVICE_CONTEXT.getPackageManager();

            Drawable appIcon = null;
            try {
                appIcon = pm.getApplicationIcon(packageName);
            } catch (Exception e) {
                Log.d("gnd", e.toString());
                //String errorMes = "\"status\": 0";
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("status", 0);
                OutputStream outputStream = m_socket.getOutputStream();
                outputStream.write(Global.JsonToByte(jsonObject));
                m_socket.close();
                return;
            }

            //int w = appIcon.getIntrinsicWidth();
            //int h = appIcon.getIntrinsicHeight();

            int w = 50;
            int h = 50;


            Bitmap.Config config = (appIcon.getOpacity() != PixelFormat.OPAQUE) ?
                    Bitmap.Config.ARGB_8888 :
                    Bitmap.Config.RGB_565;

            Bitmap bitmap = Bitmap.createBitmap(w, h, config);
            Canvas canvas = new Canvas(bitmap);
            //draw icon on the bitmap
            appIcon.setBounds(0, 0, w, h);
            appIcon.draw(canvas);

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);

            byte[] iconData = byteArrayOutputStream.toByteArray();

            JSONObject resJson = new JSONObject();
            resJson.put("status", 1);
            byte[] resJsonData = resJson.toString().getBytes("UTF-8");

            byte[] resData = new byte[4 + resJsonData.length + 1 + iconData.length];

            ByteBuffer byteBuffer = ByteBuffer.wrap(resData);
            byteBuffer.order(ByteOrder.BIG_ENDIAN);
            byteBuffer.clear();

            byteBuffer.putInt(resJsonData.length + 1 + iconData.length);
            byteBuffer.put(resJsonData);
            byteBuffer.put((byte) 0);
            byteBuffer.put(iconData);

            OutputStream outputStream = m_socket.getOutputStream();
            outputStream.write(resData);
            m_socket.close();

        } catch(Exception e)
        {
            Log.d("gnd", "failed to get icon");
        }

    }
}
